package rdb.model;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

public class ZSetObject extends BaseObject {

    private byte[][] values;
    private String[] members;
    private double[] scores;
    private HashMap<String, Double> hm;


    public ZSetObject(BaseObject baseObject, byte[][] vals) {
        super(baseObject);
        values = vals;
        members = new String[values.length / 2];
        scores = new double[values.length / 2];
        hm = new HashMap<>();
        for (int i=0,j=0;i<values.length-1;i+=2) {
            members[j] = new String(vals[i]);
            scores[j] = Double.parseDouble(new String(vals[i+1]));
            hm.put(members[j], scores[j]);
            j++;
        }

    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("ZSet: ");
        for (int i=0;i<members.length;i++) {
            sb.append(members[i])
              .append(" ")
              .append(scores[i])
              .append(" ");
        }
        sb.append("\n");
        return sb.toString();
    }

    @Override
    public Object getValue() {
        return hm;
    }

    @Override
    public String[] getCmdLines() {
        String[] ret = new String[2+hm.size()*2];
        int i = 0;
        ret[i++] = "zadd";
        ret[i++] = getKey();
        for (String member: hm.keySet()) {
            ret[i++] = Double.toString(hm.get(member));
            ret[i++] = member;
        }
        return ret;
    }
}
